//
//  DDSeverViewController.m
//  PrivateCloud
//
//  Created by sarah doo on 13-10-14.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "DDSeverViewController.h"
#import "DDSeverSubViewController.h"
#import "DDSuccessViewController.h"
#import "DDConstants.h"
#import "DDFolderInfo.h"
#import "DDVerifyThread.h"
#import "DDRefreshFile.h"
#import "DDDownLoadAddress.h"
#import "TestAddressBook.h"
#import "DDTCPListenThread.h"
#import "AppUtil.h"
#import "DDAddressBookUtils.h"
#import "TestAddressBook.h"
#import "DDContactInfosView.h"
#import "UIColor+.h"

#define TABLE_VIEW_TAG 200001
#define REFRESH_TAG 200002

@interface DDSeverViewController ()

@end

@implementation DDSeverViewController
@synthesize countArray, nameArray,hud;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    countArray = [[NSMutableArray arrayWithCapacity:0] retain];
    //    NSArray *keys = [NSArray arrayWithObjects:@"video", @"image", @"files", @"music", @"contacts", nil];
    //    for (int i = 0 ; i < [keys count]; i++) {
    //        NSDictionary *dic = [NSDictionary dictionaryWithObject:@"3" forKey:[keys objectAtIndex:i]];
    //        [array addObject:dic];
    //    }
    //MARS该数组用于存放服务器端数据的个数
    
    //array = [NSMutableArray arrayWithObjects:@"2", @"10", @"11", @"13", @"18", nil];
    [self refreshServerFileCount];
//    self.nameArray = [NSMutableArray arrayWithObjects:@"图片", @"音乐", @"视频", @"文档", @"通讯录", nil];
    self.nameArray = [[NSMutableArray alloc]init];
    [self.nameArray addObject:@"图片"];
    [self.nameArray addObject:@"音乐"];
    [self.nameArray addObject:@"视频"];
    [self.nameArray addObject:@"文档"];
    [self.nameArray addObject:@"通讯录"];
//    [self.nameArray addObject:nil];
    [self createStaticView];
}

-(void)refreshServerFileCount{
    NSArray* serverFolderInfos = [DDConstants shardServerFolderInfos];
    int photoCount = [[serverFolderInfos objectAtIndex:0]count];
    int musicCount = [[serverFolderInfos objectAtIndex:1]count];
    int fileCount = [[serverFolderInfos objectAtIndex:2]count];
    int videoCount = [[serverFolderInfos objectAtIndex:3]count];
    
    NSString* photoCountStr = [NSString stringWithFormat:@"%d",photoCount];
    NSString* musicCountStr = [NSString stringWithFormat:@"%d",musicCount];
    NSString* fileCountStr = [NSString stringWithFormat:@"%d",fileCount];
    NSString* videoCountStr = [NSString stringWithFormat:@"%d",videoCount];
    NSString* contactCountStr = [NSString stringWithFormat:@"%d",[DDConstants getServerContactCount]];
    
    UITableView* tableView = (UITableView*)[[self view]viewWithTag:TABLE_VIEW_TAG];
    //    TestAddressBook *testAddressBook = [[TestAddressBook alloc]init];
    //    int contactCount = [testAddressBook getRemoteContactCount];
    //    NSString* contactCountStr = [NSString stringWithFormat:@"%d",contactCount];
    self.countArray = [NSMutableArray arrayWithObjects:photoCountStr,musicCountStr,fileCountStr,videoCountStr,contactCountStr,nil];
    [tableView reloadData];
}

- (void)createStaticView {
    UIView *linkView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 40)];
//    linkView.backgroundColor = [UIColor greenColor];
    linkView.backgroundColor = [UIColor colorWithString:@"#273826"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:@"ico_back.png"];
    backButton.frame = CGRectMake(2, 5, 32, 32);
    [backButton setImage:image forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [linkView addSubview:backButton];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-25, 5, self.view.frame.size.width - image.size.width - 80, 30)];
    label.font = [UIFont systemFontOfSize:15];
    label.text = @"服务器";
    label.textColor = [UIColor whiteColor];
    [linkView addSubview:label];
    [label release];
    [self.view addSubview:linkView];
    
    UIButton *freshButton = [UIButton buttonWithType:UIButtonTypeCustom];
    freshButton.frame = CGRectMake(self.view.frame.size.width - 70, 0, 80, 30);
    freshButton.backgroundColor = [UIColor clearColor];
    freshButton.tag = REFRESH_TAG;
    [freshButton addTarget:self action:@selector(refreshButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *buttonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, freshButton.frame.size.width, freshButton.frame.size.height)];
    buttonLabel.textColor = [UIColor whiteColor];
    buttonLabel.font = [UIFont systemFontOfSize:15];
    buttonLabel.backgroundColor = [UIColor clearColor];
    buttonLabel.text = @"刷新";
    [freshButton addSubview:buttonLabel];
    [buttonLabel release];
    [linkView addSubview:freshButton];
    [linkView release];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(5, 60, self.view.frame.size.width - 20, 250) style:UITableViewStylePlain];
    
    tableView.delegate = self;
    tableView.scrollEnabled = NO;
    tableView.dataSource = self;
    tableView.tag = TABLE_VIEW_TAG;
    [self.view addSubview:tableView];
    [tableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 100, 34)];
    nameLabel.font = [UIFont systemFontOfSize:18];
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.text = [ self.nameArray objectAtIndex:indexPath.row];
    [cell.contentView addSubview:nameLabel];
    
    UILabel *keyLabel = [[UILabel alloc] initWithFrame:CGRectMake(668, 5, 100, 34)];
    keyLabel.font = [UIFont systemFontOfSize:18];
    keyLabel.textColor = [UIColor blackColor];
    NSString *string = [NSString stringWithFormat:@"(%@)", [self.countArray objectAtIndex:indexPath.row]];
    keyLabel.text = string;
    [cell.contentView addSubview:keyLabel];
    return cell;
}

//MARS
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int index = indexPath.row;
    if(index == 4){
        hud = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:hud];
        hud.delegate = self;
        hud.labelText = @"正在下载通讯录";
        [hud show:YES];
        
        DDVerifyThread* sendThread = [DDVerifyThread sharedVerifyThread];
        [DDTCPListenThread sharedTCPListener].downloadBookCallback = self;
        [sendThread downAddressBook];
//        [self onComplete:1];
    }
    else{
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        DDSeverSubViewController *subView = [[DDSeverSubViewController alloc] initWithNibName:nil bundle:nil];
        
        NSString* titleName = [self.nameArray objectAtIndex:indexPath.row];
        subView.titleName = titleName;
        subView.fileDataSource = [[[DDConstants shardServerFolderInfos]objectAtIndex:indexPath.row]files];
        subView.type = SERVER_CODE;
        [self presentViewController:subView animated:NO completion:nil];
        [subView release];
    }
}

- (void)backButtonPressed:(id)sender {
    DDSuccessViewController *success = [[DDSuccessViewController alloc] initWithNibName:nil bundle:nil];
    [self presentViewController:success animated:NO completion:nil];
    [success release];
}

-(void)refreshButtonPressed:(id)sender{
    //开始刷新服务器，刷新服务器需要两个操作，一个是重新下载服务器通讯录
//    [MBProgressHUD
    hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    hud.delegate = self;
    hud.labelText = @"正在刷新文件列表，请稍候。。。";
    [hud show:YES];
     
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DDTCPListenThread sharedTCPListener].refreshCallback = self;
    DDVerifyThread* sendThread = [DDVerifyThread sharedVerifyThread];
    DDRefreshFile* refreshFile = [[DDRefreshFile alloc]init];
    [sendThread sendMessage:refreshFile];
    
    DDDownLoadAddress* downloadAddress = [[DDDownLoadAddress alloc]initWithOffset:0 andLength:0xFFFFFFFF];
    [sendThread sendMessage:downloadAddress];
}

//通讯录下载完毕之后调用的回调函数
-(void)onComplete:(int)code{
    [hud hide:YES];
    //启动显示通讯录的界面
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        TestAddressBook* test = [[TestAddressBook alloc]init];
        DDAddressBookUtils* bookUtils = [[DDAddressBookUtils alloc]init];
        [bookUtils createVcfFileWithCode:LOCAL_CODE];
        NSMutableArray* contactInfos = [test loadVCF:[bookUtils getRemoteVcfPath]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            DDContactInfosView* contactView = [[DDContactInfosView alloc]initWithNibName:nil bundle:nil];
            contactView.fileDataSource = contactInfos;
            [DDConstants setServerContactCount:[contactInfos count]];
            contactView.type = SERVER_CODE;
            [self presentViewController:contactView animated:NO completion:nil];
            [contactView release];
        });
    });
    
}

-(void)onRefreshComplete:(int)code{
    UITableView* tableView = (UITableView*)[[self view]viewWithTag:TABLE_VIEW_TAG];
//    self.nameArray = [NSMutableArray arrayWithObjects:@"图片", @"音乐", @"视频", @"文档", @"通讯录", nil];
//    [self refreshServerFileCount];
    [tableView reloadData];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        TestAddressBook* test = [[TestAddressBook alloc]init];
        DDAddressBookUtils* bookUtils = [[DDAddressBookUtils alloc]init];
        [bookUtils createVcfFileWithCode:LOCAL_CODE];
        NSMutableArray* contactInfos = [test loadVCF:[bookUtils getRemoteVcfPath]];
        [DDConstants setServerContactCount:[contactInfos count]];
        //FIX ME
//            BOOL resu = [MBProgressHUD hideHUDForView:self.view animated:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self refreshServerFileCount];
            [hud hide:YES];
//            BOOL resu = [MBProgressHUD hideHUDForView:self.view animated:YES];
            [hud release];
        });
    });

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)onCompleteDealContact:(int)code{
    [self refreshServerFileCount];
}

@end
